package com.xunqi.sell.controller;

import com.xunqi.sell.form.CategoryForm;
import com.xunqi.sell.pojo.ProductCategory;
import com.xunqi.sell.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 *  卖家类目
 */

@Controller
@RequestMapping(value = "/seller/category")
public class SellCategoryController {

    @Resource
    private CategoryService categoryService;

    /**
     *  类目列表
     * @param map
     * @return
     */
    @GetMapping(value = "/list")
    public ModelAndView list(Map<String,Object> map) {
        List<ProductCategory> categoryList = categoryService.findAll();
        map.put("categoryList",categoryList);
        return new ModelAndView("category/list",map);
    }


    /**
     *  展示
     * @param categoryId
     * @param map
     * @return
     */
    @GetMapping(value = "/index")
    public ModelAndView index(@RequestParam( value = "categoryId",required = false) Integer categoryId,Map<String,Object> map) {

        if (categoryId != null) {
            ProductCategory productCategory = categoryService.findOne(categoryId);
            map.put("category",productCategory);
        }

        return new ModelAndView("category/index",map);
    }


    /**
     *  类目新增/修改
     * @param form
     * @param result
     * @param map
     * @return
     */
    @PostMapping(value = "/save")
    public ModelAndView save(@Valid CategoryForm form, BindingResult result,Map<String,Object> map) {
        //判断传过来的参数是否有问题进行效验
        if (result.hasErrors()) {
            map.put("msg",result.getFieldError().getDefaultMessage());
            map.put("url","/sell/seller/category/list");
            return new ModelAndView("common/error",map);
        }

        ProductCategory productCategory = new ProductCategory();
        try {
            if (form.getCategoryId() != null) {
                categoryService.findOne(form.getCategoryId());
            }
            BeanUtils.copyProperties(form,productCategory);
            productCategory.setId(form.getCategoryId());

            categoryService.save(productCategory);
        } catch (Exception e) {
            map.put("msg",e.getMessage());
            map.put("url","/sell/seller/category/list");
            return new ModelAndView("common/error",map);
        }
        map.put("url","/sell/seller/category/list");
        return new ModelAndView("common/success",map);
    }

}
